import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    private Socket socket = null;
    public TcpEchoClient(String serveIp , int servePort) throws IOException {
        socket = new Socket(serveIp , servePort);
        //此操作会与TCP建立连接流程,在内核中完成,在内核中完后曾连接,服务器就会从accept返回
        //由于TCP是可连接的,socket就会保存这两信息
    }
    public void start(){
        System.out.println("客户端启动!");
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()) {
            Scanner scannerConsole = new Scanner(System.in);
            Scanner scannerNetwork = new Scanner(inputStream);
            PrintWriter write = new PrintWriter(outputStream);
            while(true){
                System.out.print("->:");
                if(!scannerConsole.hasNext()){
                    break;
                }
                String request = scannerConsole.next();
                write.println(request);
                write.flush();//通过刷新保证数据发送出去了
                String response = scannerNetwork.next();
                System.out.println(response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //1.从控制台读取输入的字符串
        //2.把请求发给服务器
        //3.从服务器中读取响应
        //4.把响应显示出来
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient client = new TcpEchoClient("127.0.0.1" , 9090);
        client.start();
    }
}
